package com.sunrise.xcrm.ui.list.pagingcomponent;

import java.util.ArrayList;
import java.util.List;

import com.sunrise.xcrm.ui.list.pagingcomponent.demo.ExampleBean;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;

public class HiddenPagingContainer extends AbstractRowContainer {
    public static final int PAGE_SIZE = 100;

    List<BeanItem> currentPage = new ArrayList<BeanItem>();
    int currentPageNumber = -1;

    public HiddenPagingContainer() {
        addContainerProperty("id", Integer.class, null);
        addContainerProperty("description", String.class, null);

        setNumberOfRows(5000);
    }

    @Override
    public Item getItem(Object o) {
        Integer rowNumber = (Integer) o;
        int pageNumber = 1 + (rowNumber / PAGE_SIZE);

        if (pageNumber != currentPageNumber) {
            System.err.println("HiddenPagingContainer.getItem : Request row = " + rowNumber + ", loading page "
                    + pageNumber);
            currentPage = loadPage(pageNumber);
            currentPageNumber = pageNumber;
        }

        int currentPageIndex = rowNumber - ((currentPageNumber - 1) * PAGE_SIZE);
        return currentPage.get(currentPageIndex);
    }

    private List<BeanItem> loadPage(int pageNumber) {
        // Simulate a DB call here; we'll just sleep for half a second, which is a reasonable time for a db query to
        // last
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // No-op
        }
        List<BeanItem> items = new ArrayList<BeanItem>(PAGE_SIZE);
        for (int i = 0; i < PAGE_SIZE; i++) {
            int overallRowId = 1 + ((pageNumber - 1) * PAGE_SIZE) + i;
            items.add(new BeanItem(new ExampleBean(overallRowId, "Row " + overallRowId + ", Page #" + pageNumber)));
        }

        return items;
    }
}
